<?php
namespace app\index\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use app\common\page\Bootstrap;
class Search extends Base{
    public function __construct(\think\App $app) {
        parent::__construct($app);
        //关键词
        $keywords=Request::param("keywords","","repGet");
        if(!$keywords){
            $this->error("请输入搜索的关键词");
        }   
        View::assign("keywords",$keywords);
        
        $tables=Db::name("table")->where("table_id","in",config("search.table_id"))->select();
        $field="id,catid,modelid,link,titleurl,pagetitle,title,keywords,description,pubid,sort,is_good,is_top,views,goods,newstime,comments";
        $sql="";
        foreach($tables as $v){
            if($sql){
                $sql.=" union all ";
            }
            $sql.="select ".$field." from ".config('database.connections.mysql.prefix')."cms_".$v['table_name']." where title like '%".$keywords."%' ";
        }
        $sql.=" order by  ".config("search.order");
        
       $pageNo = Request::param('page',0,"intval");
        //客户端传过来的分页
        $pageNumber = $pageNo ? $pageNo : '0';
        if($pageNumber > 0){
            $pageNumber_one = $pageNumber-1;
        } else {
            $pageNumber_one = 0;
        }        
        $limit = config("search.lencord");//每页显示条数
        $offset = $pageNumber_one * $limit;//查询偏移值
        $count = count(Db::query($sql));//总条数
        $sql .= " limit $offset,$limit";
        $list = Db::query($sql);
        //组合分页数据格式
        $pagernator = Bootstrap::make($list,$limit,$pageNumber,$count,false,['path'=>Bootstrap::getCurrentPath(),'query'=>request()->param()]);
        $page = $pagernator->render($total=false,$pre=true,$links=true,$next=true,$listRow=false,$goPage=false);
        foreach($list as $key=>$v){
            $list[$key]['title']= str_replace($keywords,"<b>".$keywords."</b>",$v['title']);
            $list[$key]['cat']= $GLOBALS["cat"][$v['catid']];
            $list[$key]['cat']['caturl']= caturl($v['catid']);
            $list[$key]['titleurl']= titleurl($v);
        }
        // 获取分页显示
        View::assign(['data' => $list, 'page' => $page, 'total' => $count]);

    }
    public function index()
    {
        //模板
        $template_id=Db::name("template")->where(['isdefault'=>1,'type'=>'search'])->order("sort asc")->value("template_id");
        if(!$template_id){
            $this->error("模板不存在");
        }  
        return View::fetch(base_path().'data/templateFile/'.$template_id.".html");

    }
}
